// storage/upload_storage.go
package storage

import (
	"sync"
	"time"

	"file-manager/models"
)

var (
	UploadPool  = make(map[string]*models.UploadStatus) // active uploads
	uploadMutex = &sync.RWMutex{}                       // protect upload pool
)

// GetUploadStatus retrieves the status of a multipart upload
func GetUploadStatus(fileID string) *models.UploadStatus {
	uploadMutex.RLock()
	defer uploadMutex.RUnlock()
	if status, exists := UploadPool[fileID]; exists {
		return status
	}
	return nil
}

// UpdateUploadStatus updates the status of a multipart upload
func UpdateUploadStatus(fileID string, totalChunks, uploaded int) {
	uploadMutex.Lock()
	defer uploadMutex.Unlock()

	if status, exists := UploadPool[fileID]; exists {
		status.Uploaded = uploaded
		status.LastModified = time.Now()
	} else {
		UploadPool[fileID] = &models.UploadStatus{
			FileID:       fileID,
			TotalChunks:  totalChunks,
			Uploaded:     uploaded,
			LastModified: time.Now(),
		}
	}
}

// RemoveUploadStatus removes upload status from pool
func RemoveUploadStatus(fileID string) {
	uploadMutex.Lock()
	defer uploadMutex.Unlock()
	delete(UploadPool, fileID)
}

// GetAllUploadStatuses returns all active upload statuses
func GetAllUploadStatuses() map[string]*models.UploadStatus {
	uploadMutex.RLock()
	defer uploadMutex.RUnlock()
	result := make(map[string]*models.UploadStatus)
	for k, v := range UploadPool {
		result[k] = v
	}
	return result
}
